﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", ConfigFileExtension = "config", Watch = true)]
namespace PlaneClean.CommonHelp
{

    /// <summary>
    /// log4日志帮助类
    /// </summary>
    public class LogHelper
    {
        /// <summary>
        /// //这里的 loginfo 和 log4net.config 里的名字要一样
        /// </summary>
        public static readonly log4net.ILog loginfo = log4net.LogManager.GetLogger("loginfo");
        /// <summary>
        /// //这里的 logerror 和 log4net.config 里的名字要一样
        /// </summary>
        public static readonly log4net.ILog logerror = log4net.LogManager.GetLogger("logerror");
        /// <summary>
        /// 写日志记录信息
        /// </summary>
        /// <param name="info"></param>
        public static void LogInfo(string info)
        {
            if (loginfo.IsInfoEnabled)
            {
                loginfo.Info(info);
            }
        }
        /// <summary>
        /// 写程序错误异常日志
        /// </summary>
        /// <param name="info"></param>
        /// <param name="ex">异常对象</param>
        public static void LogError(string info, Exception ex)
        {
            if (logerror.IsErrorEnabled)
            {
                logerror.Error(info, ex);
            }
        }
        /// <summary>
        /// 写程序错误异常日志
        /// </summary>
        /// <param name="info"></param>
        public static void LogError(string info)
        {
            if (logerror.IsErrorEnabled)
            {
                logerror.Error(info);
            }
        }
        /// <summary>
        /// 建立线程清理日志
        /// </summary>
        public static void Dellogs()
        {
            //多线程
            Task.Factory.StartNew(() =>
            {
                DeleteLog();
            });

        }
        /// <summary>
        /// 递归删除日志
        /// </summary>
        public static void DeleteLog()
        {
            var path = AppDomain.CurrentDomain.BaseDirectory + "PlaneCleanLog\\LogError\\"; //文件夹路径
            var pathInfo = AppDomain.CurrentDomain.BaseDirectory + "PlaneCleanLog\\LogInfo\\"; //文件夹路径
            if (!Directory.Exists(path)) return;
            if (!Directory.Exists(pathInfo)) return;
            var dyInfo = new DirectoryInfo(path);
            var dyInfo1 = new DirectoryInfo(pathInfo);
            List<FileInfo> fiList = new List<FileInfo>();
            fiList.AddRange(dyInfo.GetFiles("*.htm"));
            fiList.AddRange(dyInfo1.GetFiles("*.htm"));
            foreach (var feInfo in fiList)
            {
                //早于N天 写入的文件
                if (feInfo.LastWriteTime < DateTime.Now.AddDays(-30)) feInfo.Delete();
            }
            Thread.Sleep(1000 * 60 * 60 * 24);//24小时执行一次
            DeleteLog();
        }
    }
}